package com.example.c94s3plyhyfc.util;

import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.List;

public class Utils {

    public static String getErrors(List<ObjectError> errorList, String name) {
        if(errorList==null){
            return null;
        }
        String errMsg = "";
        if (name != null && name.trim().isEmpty() == false) {
            for (ObjectError oe : errorList) {
                if (oe instanceof FieldError) {
                    FieldError fe = (FieldError) oe;
                    if (fe.getField().equals(name)) {
                        if (errMsg.isEmpty() == false) {
                            errMsg += ", ";
                        }
                        errMsg += fe.getDefaultMessage();
                    }
                }
            }
        } else {
            for (ObjectError oe : errorList) {
                if ((oe instanceof FieldError) == false) {
                    if (errMsg.isEmpty() == false) {
                        errMsg += ", ";
                    }
                    errMsg += oe.getDefaultMessage();
                }
            }
        }
        return errMsg;
    }

}
